package cn.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * 创建和关闭数据库工具类
 * @author 莫文聪
 *
 */
public class JDBCUtils {
	//final关键字修饰变量，初始化后不能更改
	//数据库地址，使用
	private static final String URL = "jdbc:mysql://localhost:3306/myblog?characterEncoding=utf-8";
	//用户名
	private static final String USERNAME = "root";
	//密码
	private static final String PASS = "asdfg.123";
	//数据库驱动
	
	/**
	 * 静态获取数据库连接
	 * @throws ClassNotFoundException
	 * @throws SQLException  直接抛掉异常
	 */
	private static final String DRIVER_CLASS="com.mysql.jdbc.Driver";
	public static Connection getConnection() throws ClassNotFoundException, SQLException {
		//加载数据库驱动
		Class.forName(DRIVER_CLASS);
		//获取数据库连接
		Connection connection = DriverManager.getConnection(URL, USERNAME, PASS);
		return connection;//返回
	}
	/**
	 * 关闭数据库连接
	 */
	public static void close(Connection connection) {
		if(connection!=null) {
			//不为空关闭
			try {
				connection.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}
